import React, { useState } from 'react';
import { Table, Button, Input, Form, Modal } from 'antd';
import { useEffect } from 'react';
import { api } from '../api/api';
import Url from '../api/url';
import { Checkbox } from 'antd';
import { message } from 'antd';

function RolePage() {
  const [roles, setRoles] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchName, setSearchName] = useState('');
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [menuModalVisible, setMenuModalVisible] = useState(false);
  const [menuOptions, setMenuOptions] = useState([]);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [editingRole, setEditingRole] = useState(null);
  const [menuForm] = Form.useForm();


  const columns = [
    { title: '角色名称', dataIndex: 'ROLENAME', key: 'ROLENAME' },
    { title: '角色编号', dataIndex: 'PK', key: 'PK' },
    { title: '菜单权限', dataIndex: 'MENUS', key: 'MENUS',render: (text, record) => {
      if (!text) return '-';
      // 将 MENUS 字符串转为数组
      const menuIds = text.split(',');
      // 从 menuOptions 中找到对应的菜单名称
      const menuNames = menuIds.map(id => 
        menuOptions.find(menu => menu.PK.toString() === id.toString())?.MENU_NAME
      ).filter(Boolean);
      return menuNames.length ? menuNames.join(', ') : '-';
    } },
  ];

  const pageLoad = async () => {

    try {
      const [result, menuRes]  = await Promise.all([
        api({url:Url.getRoles}),
        api({url:Url.getMenu})
      ])

      if(menuRes?.data){
        const menuList = menuRes?.data.map(e=> ({PK:e.PK,MENU_NAME:e.MENU_NAME}))
        setMenuOptions(menuList)
      }else{
        console.error('菜单数据为空')
        message.warning('菜单数据为空')
        setMenuOptions([])
      }

      if(result?.data){
        const roleList = result?.data.map(e=>({PK:e.PK,ROLENAME:e.ROLENAME,MENUS:e.MENUS}))
        setRoles(roleList)
      }else{
        console.error('角色数据为空')
         message.warning('角色数据为空')
        setRoles([])
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      message.error('数据加载失败')
    }
      
      
  }

  const search = async () => {
      const result = await api({url:Url.getRoles})
      const roleList = result.data.map(e=>({PK:e.PK,ROLENAME:e.ROLENAME,MENUS:e.MENUS}))
      setRoles(roleList)
  }



  const handleAdd = () => {
    setAddModalVisible(true);
    form.resetFields();
  };
  const handleAddOk = async () => {
    const values = await form.validateFields()
    const res = await api({url:Url.addRoles,data:{role:values}})
    message.success(res.msg)
    // setRoles([...roles, { PK: values.PK, ROLENAME: values.ROLENAME }]);
    search()
    setAddModalVisible(false);

  };
  const handleAddCancel = () => setAddModalVisible(false);

  const handleDelete = () => {
    if (selectedRowKeys.length === 0) return;
    const role = roles.find(u => u.PK === selectedRowKeys[0]);
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${selectedRowKeys.length}个角色吗？`,
      onOk: async () => {
        const res = await api({url:Url.delRoles,data:{role:role}})
        message.success(res.msg)
        setRoles(roles.filter(r => !selectedRowKeys.includes(r.PK)));
        setSelectedRowKeys([]);
      },
    });
  };

  // const handleEdit = () => {
  //   if (selectedRowKeys.length !== 1) {
  //     Modal.info({ title: '提示', content: '请选择一条要修改的数据' });
  //     return;
  //   }
  //   const role = roles.find(r => r.PK === selectedRowKeys[0]);
  //   setEditingRole(role.PK);
  //   editForm.setFieldsValue({ ...role });
  //   setEditModalVisible(true);
  // };
  // const handleEditOk = () => {
  //   editForm.validateFields().then(values => {
  //     setRoles(roles.map(r => r.PK === editingRole ? { ...r, ...values } : r));
  //     setEditModalVisible(false);
  //     setSelectedRowKeys([]);
  //   });
  // };
  // const handleEditCancel = () => setEditModalVisible(false);

  const handleAssignMenu = () => {
    if (selectedRowKeys.length !== 1) {
      Modal.info({ title: '提示', content: '请选择一条要分配菜单的数据' });
      return;
    }
    // 假设角色有menus字段
    const role = roles.find(r => r.PK === selectedRowKeys[0]);
    // 将逗号分隔的菜单ID字符串转为数组
    const menuIds = role.MENUS ? role.MENUS.split(',').map(id => Number(id)) : [];
    menuForm.setFieldsValue({ menus: menuIds || [] });
    setMenuModalVisible(true);
  };

  const handleMenuOk = async () => {
    const values = await menuForm.validateFields()
    const role = roles.find(r => r.PK === selectedRowKeys[0]);
    role.MENUS = values.menus.toString()

    const res = await api({url:Url.roleMenus,data:{role:role}})
    message.success(res.msg)

    setRoles(roles.map(r => r.PK === selectedRowKeys[0] ? { ...r, menus: values.menus } : r));
    setMenuModalVisible(false);
    setSelectedRowKeys([]);
  };

  const handleMenuCancel = () => setMenuModalVisible(false);
  const filteredRoles = roles.filter(r => r.ROLENAME?.includes(searchName));


  useEffect(() => {
      pageLoad()
  },[])

  return (
    <div style={{ padding: 0, background: '#f5f6fa'}}>
      <div style={{ marginBottom: 16, background: '#fff', padding: 16, borderRadius: 8, display: 'flex', alignItems: 'center' }}>
        <span style={{ marginRight: 8 }}>角色名称:</span>
        <Input value={searchName} onChange={e => setSearchName(e.target.value)} style={{ width: 200, marginRight: 8 }} />
        <Button type="primary" onClick={search}>检索</Button>
      </div>
      <div style={{ marginBottom: 8, background: '#fff', padding: 8, borderRadius: 8 }}>
        <Button type="primary" onClick={handleAdd}>添加</Button>
        <Button danger style={{ marginLeft: 8 }} onClick={handleDelete} disabled={selectedRowKeys.length === 0}>删除</Button>
        {/* <Button style={{ marginLeft: 8 }} onClick={handleEdit}>修改</Button> */}
        <Button style={{ marginLeft: 8 }} onClick={handleAssignMenu}>分配菜单</Button>
      </div>
      <Table
        rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
        columns={columns}
        dataSource={filteredRoles}
        bordered
        rowKey={'PK'}
        pagination={{ pageSize: 10 }}
        style={{ background: '#fff', borderRadius: 8 }}
        scroll={{ x: 'max-content' }}
      />
      <Modal
        title="添加角色"
        open={addModalVisible}
        onOk={handleAddOk}
        onCancel={handleAddCancel}
        okText="保存"
        cancelText="取消"
        destroyOnHidden
        forceRender
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} clearOnDestroy >
          {/* <Form.Item label="角色编号" name="key" rules={[{ required: true, message: '请输入角色编号' }]}> 
            <Input /> 
            </Form.Item> */}
          <Form.Item label="角色名称" name="ROLENAME" rules={[{ required: true, message: '请输入角色名称' }]}> 
            <Input /> 
            </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="修改角色"
        open={editModalVisible}
        // onOk={handleEditOk}
        // onCancel={handleEditCancel}
        okText="保存"
        cancelText="取消"
        destroyOnHidden
        forceRender
      >
        <Form form={editForm} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} clearOnDestroy >
          {/* <Form.Item label="角色编号" name="key" rules={[{ required: true, message: '请输入角色编号' }]}> 
            <Input disabled /> 
            </Form.Item> */}
          <Form.Item label="角色名称" name="ROLENAME" rules={[{ required: true, message: '请输入角色名称' }]}>
             <Input /> 
             </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="分配菜单"
        open={menuModalVisible}
        onOk={handleMenuOk}
        onCancel={handleMenuCancel}
        okText="保存"
        cancelText="取消"
        destroyOnHidden
        forceRender
      >

        <Form form={menuForm} labelCol={{ span: 0 }} wrapperCol={{ span: 24 }} clearOnDestroy>
          <Form.Item name="menus" rules={[{ required: true, message: '请选择菜单' }]}> 
            <Checkbox.Group style={{ width: '100%' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24 }}>
                {menuOptions.map(menu => (
                  <Checkbox key={menu.PK} value={menu.PK} style={{ minWidth: 120, marginBottom: 12 }}>{menu.MENU_NAME}</Checkbox>
                ))}
              </div>
            </Checkbox.Group>
          </Form.Item>
        </Form>



      </Modal>
    </div>
  );
}

export default RolePage;
